import Parameter from 'parameter'
import {Context, Next} from 'TYPE'
// import {I18n} from 'i18n'

export const parameter = new Parameter({
    // translate: function() {
    //   var args = Array.prototype.slice.call(arguments);
    //   // Assume there have I18n.t method for convert language.
    //   return I18n.apply(I18n, args);
    // },
    validateRoot: true, // restrict the being validate value must be a object
    convert: true
})
parameter.addRule('array_uint', ((rule: any, v: any, obj: any) => {
    // console.log(rule);
    // console.log(v);
    // console.log(obj);
    for (const k of Object.keys(obj)) {
        if(!k.endsWith('[]')) continue
        if (!Array.isArray(obj[k])) {
            obj[k] = [obj[k]]
        }
        for (let i = 0; i < obj[k].length; i++) {
            const oldValue = obj[k][i] + ''
            obj[k][i] = Number(obj[k][i])
            if ((!obj[k][i] && obj[k][i] !== 0) || obj[k][i] < 0) {
                return oldValue +' should be an integer array'
            }
        }
    }


}) as any);

export const validateQuery = (rule: any) => {
    return function (target: any, methodName: string, desc: PropertyDescriptor) {
        let curMethod = desc.value
        desc.value = async function (ctx: Context, next: Next) {
            next = next || (() => {}) as any
            var errors = parameter.validate(rule, ctx.query)
            if (errors) {
                ctx.cd = -2
                ctx.msg = errors[0].field + ' ' + errors[0].message
                await next()
                return
            }
            ctx.validatedParams = ctx.validatedParams || {}
            ctx.validatedParams = {...ctx.validatedParams, ...ctx.query}
            await curMethod.call(target, ctx, next)
        }
    }
}
export const validateBody = (rule: any) => {
    return function (target: any, methodName: string, desc: PropertyDescriptor) {
        let curMethod = desc.value
        desc.value = async function (ctx: Context, next: Next) {
            next = next || (() => {}) as any
            var errors = parameter.validate(rule, ctx.request.body)
            if (errors) {
                ctx.cd = -2
                ctx.msg = errors[0].field + ' ' + errors[0].message
                await next()
                return
            }
            ctx.validatedParams = ctx.validatedParams || {}
            ctx.validatedParams = {...ctx.validatedParams, ...ctx.request.body}
            await curMethod.call(target, ctx, next)
        }
    }
}
// export default parameter
